package com.kkb.util;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Aspect
public class LogUtils {
    // 配置切入点表达式
    @Pointcut("execution(* com.kkb.service..*.*(..))")
    public void pointCut(){};

//    @Before("pointCut()")
    public void beforePrintLog(JoinPoint joinPoint) throws Throwable{
        // 获取切入点方法参数
        Object[] args = joinPoint.getArgs();
        System.out.println("LogUtils前置通知" + Arrays.toString(args));
    }

//    @AfterReturning(value = "pointCut()",returning = "returnValue")
    public void afterReturnPrintLog(JoinPoint joinPoint, Object returnValue) throws Throwable{
        System.out.println("LogUtils后置通知,方法返回值为：" + returnValue);
    }

//    @AfterThrowing(value = "pointCut()", throwing = "e" )
    public void afterThrowingPrintLog(JoinPoint joinPoint, Throwable e) throws Throwable{
        System.out.println("LogUtils异常通知");
        e.printStackTrace();
    }

//    @After("pointCut()")
    public void afterPrintLog(JoinPoint joinPoint){
        System.out.println("LogUtils最终通知");
    }

    //环绕通知: 作用, 自己指定 执行如何执行
    @Around("pointCut()")
    public Object aroundPrintLog(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = null;
        try {
            //  开启事务, 前置通知
            this.beforePrintLog(joinPoint);
            //获取参数
            Object[] args = joinPoint.getArgs();
            // 让切入点方法执行, service层的 addAccount方法, deleteAccount方法, updateAccount方法, findAccount方法
            result = joinPoint.proceed(args);
            //  提交事务, 后置通知执行
            this.afterReturnPrintLog(joinPoint, result);
        } catch (Throwable t) {
            //  事务回滚, 异常通知的执行
            t.printStackTrace();
            this.afterThrowingPrintLog(joinPoint, t);
        } finally {
            // 资源释放, 最终通知的执行
            this.afterPrintLog(joinPoint);
        }
        return result;
    }
}
